package code.wrtp.packets;

import code.exceptions.BadPduFormatException;
import code.wrtp.FrameControlType;

public class Elected implements Packet {

	private byte FC; /* Frame control field */
	private short SA; /* Source Address field */
	private short RA; /* Ring Address */
	private short DA; /* Destination Address */
	private short nodeElected; /* Node elected */

	public Elected(byte FC, short SA, short RA, short DA, short nodeElected) {
		this.FC = FC;
		this.SA = SA;
		this.RA = RA;
		this.DA = DA;
		this.nodeElected = nodeElected;
	}

	public byte getFC() {
		return FC;
	}

	public short getSA() {
		return SA;
	}

	public short getRA() {
		return RA;
	}

	public short getDA() {
		return DA;
	}

	public short getNodeElected() {
		return nodeElected;
	}

	@Override
	public byte[] toBytes() {
		return toString().getBytes();
	}

	@Override
	public String toString() {
		String token = FC + ";" + RA + ";" + DA + ";" + SA + ";" + nodeElected;
		return token;
	}

	@Override
	public void ParseBytes(byte[] pduRaw) throws BadPduFormatException {
String[] splittedPacket = new String(pduRaw).split(";",5);
		
		if (splittedPacket.length != 5) {
			throw new BadPduFormatException("Wrong packet format");
		}
		
		FC = Byte.parseByte(splittedPacket[0]);
		if ((FC != FrameControlType.ELECTED_TOKEN) && (FC != FrameControlType.VARAL_ELECTED_TOKEN))
			throw new BadPduFormatException("Wrong packet format");
		RA = Short.parseShort(splittedPacket[1]);
		DA = Short.parseShort(splittedPacket[2]);
		SA = Short.parseShort(splittedPacket[3]);
		nodeElected = Short.parseShort(splittedPacket[4]);
	}
}